<?php
/* $Id$ */
/*
	traffic.php
	part of stairway

	Copyright (C) 2009 Wang Zhongliang (wzlsh629@163.com)
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.
*/

##|+PRIV
##|*IDENT=page-traffic
##|*NAME=traffic page
##|*DESCR=Allow access to the 'Traffci' page.
##|*MATCH=traffic.php*
##|-PRIV

require_once('guiconfig.inc');

function parse_traffic_file($file, $direct = 'in')
{
	$arr = array();
	$lines = file($file);
	foreach($lines as $line)
	{
		sscanf($line, "%s %s %s", $ip, $pkts, $byts);
		$arr[$ip][$direct] = array('packets' => $pkts, 'bytes' => $byts);
	}
	return $arr;
}

function calc_realtime_traffic($now, $past, $inteval = 10)
{
	foreach($now as $key => $value)
	{
		$now[$key]['in']['packets'] -= $past[$key]['in']['packets'];
		$now[$key]['in']['packets'] = (int)($now[$key]['in']['packets'] / $inteval);
		$now[$key]['in']['bytes'] -= $past[$key]['in']['bytes'];
		$now[$key]['in']['bytes'] = (int)($now[$key]['in']['bytes'] / $inteval);
		$now[$key]['out']['packets'] -= $past[$key]['out']['packets'];
		$now[$key]['out']['packets'] = (int)($now[$key]['out']['packets'] / $inteval);
		$now[$key]['out']['bytes'] -= $past[$key]['out']['bytes'];
		$now[$key]['out']['bytes'] = (int)($now[$key]['out']['bytes'] / $inteval);
	}
	return $now;
}

if(strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
{
	if($_POST['enable'])
	{
		$config['pmacctd']['enable'] = "";

		write_config();

		services_pmacctd_configure();		
	}
	else
	{
		unset($config['pmacctd']['enable']);

		write_config();

		services_pmacctd_configure();
	}
}

if(isset($config['captiveportal']['enable']) && $config['captiveportal']['auth_method'] != 'none')
{
    $show_cpname = true;
}

if($_GET['act'] == 'reset')
{
	services_pmacctd_configure();
}

if(isset($config['pmacctd']['enable']))
{
    $c = 0;
    while(file_exists("{$g['vardb_path']}/pmacctd/pmacct.lock"))
    {
        usleep(500000);
        if($c++ > 10)
            break;
    }
	$in_now = parse_traffic_file("{$g['vardb_path']}/pmacctd/in.now");
	$in_past = parse_traffic_file("{$g['vardb_path']}/pmacctd/in.past");
	$out_now = parse_traffic_file("{$g['vardb_path']}/pmacctd/out.now", "out");
	$out_past = parse_traffic_file("{$g['vardb_path']}/pmacctd/out.past", "out");
	
	$total = array_merge_recursive($in_now, $out_now);
	$total_last = array_merge_recursive($in_past, $out_past);
	$realtime = calc_realtime_traffic($total, $total_last);
	
	$state = `pfctl -s state | grep "\->"  | awk '{print substr($3,0,index($3, ":")-1), $2}' | sort | uniq -c | grep -E '( 172\.16| 192\.168\.| 10.)'`;
	$conn = array();
	foreach(explode("\n", $state) as $line)
	{
		sscanf($line, "%d %s %s", $num, $ip, $proto);
		$conn[$ip][$proto] = $num;
	}
	foreach($conn as &$value)
	{
		$value['total'] = $value['tcp'] + $value['udp'];
	}
	
	$sort = (int)$_GET['sort'];
	$sort_value = array();
	foreach ($total as $key => $row)
	{
		switch($sort)
		{
			case 0:
				$sort_value[$key] = ip2long($key);
				break;
			case 1:
				$sort_value[$key] = $row['in']['bytes'];
				break;
			case 2:
				$sort_value[$key] = $row['in']['packets'];
				break;
			case 3:
				$sort_value[$key] = $row['out']['bytes'];
				break;
			case 4:
				$sort_value[$key] = $row['out']['packets'];
				break;
			case 5:
				$sort_value[$key] = $realtime[$key]['in']['bytes'];
				break;
			case 6:
				$sort_value[$key] = $realtime[$key]['in']['packets'];
				break;
			case 7:
				$sort_value[$key] = $realtime[$key]['out']['bytes'];
				break;
			case 8:
				$sort_value[$key] = $realtime[$key]['out']['packets'];
				break;
			case 9:
				$sort_value[$key] = $conn[$key]['total'];
				break;
			case 10:
				$sort_value[$key] = $conn[$key]['tcp'];
				break;
			case 11:
				$sort_value[$key] = $conn[$key]['udp'];
				break;
		}
	}
	
	array_multisort($sort_value, $sort ? SORT_DESC : SORT_ASC, $total);
	
	$clients = get_client_by_time();

}
$pgtitle = array("流量管理", "客户端流量");
$pgmenu = array('traffic', '/traffic_monitor.php');
include("head.inc");
?>

<body link="#0000CC" vlink="#0000CC" alink="#0000CC">
<?php include("fbegin.inc");?>
<div class="soft_cont_right_table">
<table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr>
        	<form method="post" action="traffic_monitor.php">
        	<td class="listhdrr">
            	<input name="enable" type="checkbox" <?php if(isset($config['pmacctd']['enable'])) echo "checked"; ?>>启用客户端流量统计
            </td>
            <td class="listhdrr">
            	<input type="submit" value="保存">
            </td>
            </form>
        </tr>
        <tr>
        	<td class="listhdrr">
        	<form name="form1">
        		<select name="sort" onchange="document.form1.submit();">
        			<option value="0" <?php if($sort == 0) echo "selected";?>>按IP地址排序</option>
        			<option value="1" <?php if($sort == 1) echo "selected";?>>按总下载字节数排序</option>
        			<option value="2" <?php if($sort == 2) echo "selected";?>>按总下载数据包排序</option>
        			<option value="3" <?php if($sort == 3) echo "selected";?>>按总上传字节数排序</option>
        			<option value="4" <?php if($sort == 4) echo "selected";?>>按总上传数据包排序</option>
        			<option value="5" <?php if($sort == 5) echo "selected";?>>按当前下载字节数排序</option>
        			<option value="6" <?php if($sort == 6) echo "selected";?>>按当前下载数据包排序</option>
        			<option value="7" <?php if($sort == 7) echo "selected";?>>按当前上传字节数排序</option>
        			<option value="8" <?php if($sort == 8) echo "selected";?>>按当前上传数据包排序</option>
        			<option value="9" <?php if($sort == 9) echo "selected";?>>按总连接数排序</option>
        			<option value="10" <?php if($sort == 10) echo "selected";?>>按TCP连接数排序</option>
        			<option value="11" <?php if($sort == 11) echo "selected";?>>按UDP连接数排序</option>
        		</select>
        	</form>
        	</td>
        	<td class="listhdrr"><input type="button" value="刷新" onclick="window.location='traffic_monitor.php?sort=<?=$sort;?>';"><input type="button" value="清零" onclick="window.location='traffic_monitor.php?act=reset';"></td>
        </tr>
        <tr>
            <td><br></td>
        </tr>
        <tr>
	        <td colspan="2">
		        <table width="100%" border="0" cellpadding="0" cellspacing="0">
					<tr>
						<td class="listhdrr" align="center" rowspan="3">IP地址</td>
						<td class="listhdrr" align="center" rowspan="3">主机名称</td>
						<?php if($show_cpname): ?><td class="listhdrr" align="center" rowspan="3">认证用户</td><?php endif; ?>
						<td class="listhdrr" align="center" colspan="4">总流量</td>
						<td class="listhdrr" align="center" colspan="4">当前流量（单位：每秒）</td>
						<td class="listhdrr" align="center" rowspan="2" colspan="3">连接数</td>
					</tr>
					<tr>
						<td class="listhdrr" align="center" colspan="2">数据包数</td>
						<td class="listhdrr" align="center" colspan="2">字节数</td>
						<td class="listhdrr" align="center" colspan="2">数据包数</td>
						<td class="listhdrr" align="center" colspan="2">字节数</td>
					</tr>
					<tr>
						<td class="listhdrr" align="center">上行</td>
						<td class="listhdrr" align="center">下行</td>
						<td class="listhdrr" align="center">上行</td>
						<td class="listhdrr" align="center">下行</td>
						<td class="listhdrr" align="center">上行</td>
						<td class="listhdrr" align="center">下行</td>
						<td class="listhdrr" align="center">上行</td>
						<td class="listhdrr" align="center">下行</td>
						<td class="listhdrr" align="center">总连接</td>
						<td class="listhdrr" align="center">TCP</td>
						<td class="listhdrr" align="center">UDP</td>
					</tr>
					<?php foreach($total as $ip => $item): ?>
					<tr>
						<td class="listlr" align="center"><?=$ip;?></td>
						<td class="listlr" align="center"><?=$clients[$ip]['nbtname'] ? $clients[$ip]['nbtname'] : $clients[$ip]['dhcpname'];?></td>
						<?php if($show_cpname): ?><td class="listlr" align="center"><?=$clients[$ip]['cpname'];?></td><?php endif ?>
						<td class="listlr" align="center"><?=(int)$item['out']['packets'];?></td>
						<td class="listlr" align="center"><?=(int)$item['in']['packets'];?></td>
						<td class="listlr" align="center"><?=(int)$item['out']['bytes'];?></td>
						<td class="listlr" align="center"><?=(int)$item['in']['bytes'];?></td>
						<td class="listlr" align="center"><?=(int)$realtime[$ip]['out']['packets'];?></td>
						<td class="listlr" align="center"><?=(int)$realtime[$ip]['in']['packets'];?></td>
						<td class="listlr" align="center"><?=(int)$realtime[$ip]['out']['bytes'];?></td>
						<td class="listlr" align="center"><?=(int)$realtime[$ip]['in']['bytes'];?></td>
						<td class="listlr" align="center"><?=(int)$conn[$ip]['total'];?></td>
						<td class="listlr" align="center"><?=(int)$conn[$ip]['tcp'];?></td>
						<td class="listlr" align="center"><?=(int)$conn[$ip]['udp'];?></td>
					</tr>
					<?php endforeach; ?>
					<tr><td class="listlr" align="right" colspan="13">共 <?=count($total);?> 条记录&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>	
		        </table>
	        </td>
        </tr>
</table>
</div>
<?php include("fend.inc"); ?>
</body>
</html>
